var gPendingCallbacks = [];
var bkg = chrome.extension.getBackgroundPage();
var last_credentials = [];

chrome.webRequest.onAuthRequired.addListener(handleAuthRequest,
	{urls: ["<all_urls>"]}, ["asyncBlocking"]);

function processPendingCallbacks() {
	var cb_data = gPendingCallbacks.pop();
	var server_address = cb_data.details.challenger.host+":"+cb_data.details.challenger.port;
	var credentials_rx = /([A-z0-9]*):?([A-z0-9]*)@.+/i;
	var credentials = credentials_rx.exec(cb_data.details.url);
	
	if(credentials!=null && (!last_credentials[server_address] || credentials[1]+":"+credentials[2]!=last_credentials[server_address])){
		last_credentials[server_address] = credentials[1]+":"+credentials[2];
		var headerData = new Object();
		headerData.username=credentials[1];
		headerData.password=credentials[2];
		cb_data.callback({authCredentials:headerData});
	} else {
		delete last_credentials[server_address];
		cb_data.callback({});
	}
}

function handleAuthRequest(details, callback) {
	gPendingCallbacks.push({callback:callback, details:details});
	processPendingCallbacks();
}